# coding=utf-8
import tormysql
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.log
import tornado.options
import tornado.locale
import argparse
import os
import base64
import hashlib
from public_libs.Log_Handler import Log_Handler
import config

# 定义一个默认的端口
parser = argparse.ArgumentParser(description='Project to th is script')
parser.add_argument('-db_host', type=str, default=config.MYSQL.get("host"), help="Project database host")
parser.add_argument('-db_port', type=int, default=config.MYSQL.get("post"), help="Project database port")
parser.add_argument('-db_database', type=str, default=config.MYSQL.get("database"), help="Project database name")
parser.add_argument('-db_user', type=str, default=config.MYSQL.get("user"), help="database user")
parser.add_argument('-db_password', type=str, default=config.MYSQL.get("password"), help="database password")
parser.add_argument('-port', type=int, default=80, help="server port")

options = parser.parse_args()

# 自定义log
Log_Handler(tornado.log.gen_log, log_file_path=os.path.join(os.path.dirname(__file__), "logs/main.log")).Timed_day_logger()
Log_Handler(tornado.log.access_log, log_file_path=os.path.join(os.path.dirname(__file__), "logs/main.log")).Timed_day_logger()
Log_Handler(tornado.log.app_log, log_file_path=os.path.join(os.path.dirname(__file__), "logs/main.log")).Timed_day_logger()

tornado.log.app_log.warning(options)

config.settings["log"] = tornado.log


tornado.log.app_log.warning("当前环境 %s" % config.env)


class Application(tornado.web.Application):

    def __init__(self):
        self.db = self.maybe_create_tables()
        cookie_secret = base64.b64encode(bytes(hashlib.md5(bytes(config.settings.__str__(), encoding="utf-8")).hexdigest(), encoding="utf-8"))
        config.settings["cookie_secret"] = cookie_secret
        config.settings["server_post"] = options.port
        tornado.log.app_log.warning("settings:")
        for i in config.settings.items():
            tornado.log.app_log.warning(i)
        super(Application, self).__init__(**config.settings)

    def maybe_create_tables(self):
        return tormysql.ConnectionPool(
            max_connections=100,
            port=options.db_port,
            host=options.db_host,
            user=options.db_user,
            passwd=options.db_password,
            db=options.db_database,
            charset="utf8"
        )


if __name__ == "__main__":
    app = Application()
    http_server = tornado.httpserver.HTTPServer(app)
    tornado.log.app_log.warning('start server 127.0.0.1:%s...' % options.port)
    http_server.listen(options.port, address="0.0.0.0")
    tornado.ioloop.IOLoop.configure('tornado.platform.asyncio.AsyncIOLoop')
    tornado.ioloop.IOLoop.current().start()
